package com.alipay.rebate.shop.service.common;

import com.alipay.rebate.shop.constants.CommonConstant;
import com.alipay.rebate.shop.constants.UserContant;
import com.alipay.rebate.shop.dao.mapper.UserMapper;
import com.alipay.rebate.shop.model.User;
import com.alipay.rebate.shop.pojo.user.customer.UserDto;
import com.alipay.rebate.shop.utils.JwtUtils;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;

public abstract class AbstractUserService implements UserService {

  private Logger logger = LoggerFactory.getLogger(AbstractUserService.class);

  @Autowired
  protected UserMapper userMapper;
  @Autowired
  protected StringRedisTemplate stringRedisTemplate;

  @Override
  public Long insert(User user) {
    return userMapper.insertUser(user);
  }

  @Override
  @Transactional
  public int update(User user) {
    return userMapper.updateUser(user);
  }

  @Override
  @Transactional
  public int delete(Long id) {
    return userMapper.deleteUserById(id);
  }

  @Override
  public User get(Long id) {
    return userMapper.selectById(id);
  }

  /**
   * 给http response header设置token 信息
   *
   * @param response
   * @param subject
   */
  protected void generateTokenAndSetIngoHeader(
      HttpServletResponse response,
      Subject subject,
      String type
  ) {
    UserDto user = (UserDto) subject.getPrincipal();
    logger.debug("Login getPrincipal is : {}", user);
    // 生成token
    String accessToken = JwtUtils.sign(
        String.valueOf(user.getUserId()), type,
        CommonConstant.JWT_SALT,
        CommonConstant.ACCESS_TOKEN_EXPIRE_TIME);
    String refreshToken = JwtUtils.sign(
        String.valueOf(user.getUserId()), type,
        CommonConstant.JWT_SALT,
        CommonConstant.REFRESH_TOKEN_EXPIRE_TIME);
    // 设置到x-auth-token header中返回给客户端
    logger.debug("Login accessToken is : {}", accessToken);
    logger.debug("Login refreshToken is : {}", refreshToken);
    logger.debug("userDto is : {}", user);
    response.setHeader(CommonConstant.ACCESS_HEADER_KEY, accessToken);
    response.setHeader(CommonConstant.AUTH_HEADER_KEY, accessToken);
    response.setHeader(CommonConstant.REFRESH_HEADER_KEY, refreshToken);
  }

  /**
   * TODO(Mingweicai)
   * 获取用户角色列表，强烈建议从缓存中获取
   *
   * @param userId
   * @return
   */
  @Override
  public List<String> getUserRoles(Long userId) {
    logger.debug("");
    User user = userMapper.selectById(userId);
    logger.debug("get user roles: user is : {}",user);
    if(UserContant.ADMIN_USER_TYPE == user.getUserType() ){
      return Arrays.asList("admin");
    }
    return Arrays.asList("customer");
  }

  /**
   * 获取上次token生成时的salt值和登录用户信息
   *
   * @return
   */
  @Override
  public UserDto getJwtTokenInfo(String id) {
    UserDto user = userMapper.selectUserDtoInfoById(Long.valueOf(id));
    user.setSalt(CommonConstant.JWT_SALT);
    return user;
  }

  public String generateMobileCode() {
    return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
  }

}
